package com.gxar.quick.ar.server.db.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.gxar.common.entity.PageResult;
import com.gxar.common.entity.Result;
import com.gxar.common.entity.SlippageResult;
import com.gxar.common.entity.login.UserProfile;
import com.gxar.common.exception.APIRuntimeException;
import com.gxar.common.utils.PageUtils;
import com.gxar.common.utils.SnowFlakeUtils;
import com.gxar.fusion.redis.service.RedisService;
import com.gxar.quick.ar.server.base.common.constant.RedisConstant;
import com.gxar.quick.ar.server.base.common.constant.WorksConstant;
import com.gxar.quick.ar.server.base.common.enums.*;
import com.gxar.quick.ar.server.base.common.enums.order.*;
import com.gxar.quick.ar.server.base.model.ResultCodeEnum;
import com.gxar.quick.ar.server.base.model.order.dto.ExchangeOrderConfigDTO;
import com.gxar.quick.ar.server.base.model.order.vo.request.OrderCreateRequest;
import com.gxar.quick.ar.server.base.model.works.mapper.WorksTemplateMapStruct;
import com.gxar.quick.ar.server.base.model.works.vo.request.WorksTemplateCreateRequest;
import com.gxar.quick.ar.server.base.model.works.vo.request.WorksTemplateUpdateRequest;
import com.gxar.quick.ar.server.base.model.works.vo.response.WorksTemplateCreateResponse;
import com.gxar.quick.ar.server.base.model.works.vo.response.WorksTemplateInfoResponse;
import com.gxar.quick.ar.server.base.model.works.vo.response.WorksTemplateListResponse;
import com.gxar.quick.ar.server.db.mapper.ExchangeItemMapper;
import com.gxar.quick.ar.server.base.model.works.vo.response.WorksTemplateUpdateResponse;
import com.gxar.quick.ar.server.db.mapper.ExchangeItemUserMapper;
import com.gxar.quick.ar.server.db.mapper.ExchangeItemWorksMapper;
import com.gxar.quick.ar.server.db.mapper.WorksTemplateMapper;
import com.gxar.quick.ar.server.db.model.*;
import com.gxar.quick.ar.server.db.repository.*;
import com.gxar.quick.ar.server.db.model.WorksEntity;
import com.gxar.quick.ar.server.db.model.WorksTemplateEntity;
import com.gxar.quick.ar.server.db.repository.WorksRepository;
import com.gxar.quick.ar.server.db.repository.WorksTemplateRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author linsy
 * @version 1.0
 * @created 2023/11/8 16:04
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class WorksTemplateService {

    private final RedisService redisService;

    private final WorksTemplateMapper worksTemplateMapper;

    private final WorksTemplateRepository worksTemplateRepository;

    private final WorksRepository worksRepository;

    /**
     * 模板列表查询
     *
     * @param userProfile     用户信息
     * @param nextId          下一页
     * @param productCategory 产品类别
     * @return 响应
     */
    public SlippageResult<WorksTemplateListResponse> templateList(UserProfile userProfile, String nextId, String productCategory) {
        int pageNumber = 1;
        if (StringUtils.isNotBlank(nextId)) {
            String pageKey = String.format(RedisConstant.WORKS_TEMPLATE_PAGE_KEY, nextId);
            Object pageInfo = redisService.get(pageKey);
            if (pageInfo != null) {
                pageNumber = Integer.parseInt(pageInfo.toString());
                redisService.remove(pageKey);
            }
        }
        PageHelper.startPage(pageNumber, WorksConstant.DEFAULT_QUERY_LIMIT);
        int productCategoryCode = 0;
        if (StringUtils.isNotBlank(productCategory)) {
            productCategoryCode = Integer.parseInt(productCategory);
        }
        List<WorksTemplateEntity> worksTemplateEntities = worksTemplateMapper.queryPage(productCategoryCode);
        if (CollectionUtils.isEmpty(worksTemplateEntities)) {
            return SlippageResult.build(null, Collections.emptyList());
        }
        List<WorksTemplateListResponse> response = WorksTemplateMapStruct.INSTANCE.entityToListResponses(worksTemplateEntities);
        String nextedId = SnowFlakeUtils.getInstance().nextId();
        String pageKey = String.format(RedisConstant.WORKS_TEMPLATE_PAGE_KEY, nextedId);
        redisService.set(pageKey, pageNumber + 1);
        redisService.expire(pageKey, RedisConstant.DEFAULT_EXPIRE_SECONDS);
        return SlippageResult.build(nextedId, response);
    }

    /**
     * 获取作品模板详情
     *
     * @param userProfile 用户信息
     * @param id          模板id
     * @return 响应
     */
    public Result<WorksTemplateInfoResponse> getTemplateDetail(UserProfile userProfile, Long id) {
        Optional<WorksTemplateEntity> worksTemplateEntityOptional = worksTemplateRepository.findById(id);
        if (worksTemplateEntityOptional.isPresent()) {
            WorksTemplateEntity worksTemplateEntity = worksTemplateEntityOptional.get();
            WorksTemplateInfoResponse worksDraftInfoResponse = WorksTemplateMapStruct.INSTANCE.entityToInfoResponse(worksTemplateEntity);
            return Result.success(worksDraftInfoResponse);
        }
        return Result.error(ResultCodeEnum.WORK_TEMPLATE_NOT_EXIST);
    }

    /**
     * 分页查询
     *
     * @param userProfile     用户信息
     * @param pageNum         当前页
     * @param pageSize        页记录数
     * @param productCategory 产品类别
     * @return 响应
     */
    public Result<PageResult<WorksTemplateListResponse>> pageList(UserProfile userProfile, Integer pageNum, Integer pageSize, String productCategory) {
        Page<Object> page = PageHelper.startPage(pageNum, pageSize);
        List<WorksTemplateEntity> worksTemplateEntities = worksTemplateMapper.queryPage(StringUtils.isNotBlank(productCategory) ? Integer.parseInt(productCategory) : null);
        if (CollectionUtils.isEmpty(worksTemplateEntities)) {
            return Result.success(new PageResult<>());
        }
        List<WorksTemplateListResponse> worksTemplateListResponses = WorksTemplateMapStruct.INSTANCE.entityToListResponses(worksTemplateEntities);
        PageInfo<WorksTemplateListResponse> worksTemplateListResponsePageInfo = new PageInfo<>(worksTemplateListResponses);
        worksTemplateListResponsePageInfo.setPageNum(pageNum);
        worksTemplateListResponsePageInfo.setTotal(page.getTotal());
        return PageUtils.getPageResult(worksTemplateListResponsePageInfo, worksTemplateListResponses);
    }

    /**
     * 创建模板
     *
     * @param userProfile 用户信息
     * @param request     请求
     * @return 响应
     */
    public WorksTemplateCreateResponse createTemplate(UserProfile userProfile, WorksTemplateCreateRequest request) {
        Long worksId = request.getWorksId();
        Optional<WorksEntity> worksEntityOptional = worksRepository.findById(worksId);
        if (!worksEntityOptional.isPresent()) {
            throw new APIRuntimeException(ResultCodeEnum.WORK_NOT_EXIST);
        }
        Integer sort = worksTemplateMapper.findLastSort();
        WorksTemplateEntity entity = WorksTemplateMapStruct.INSTANCE.createToEntity(request);
        entity.setId(Long.parseLong(SnowFlakeUtils.getInstance().nextId()));
        entity.setSort(sort + 1);
        entity.setCreatedAt(new Date());
        entity.setCreator(userProfile.getMobile());
        entity.setUpdatedAt(new Date());
        entity.setIdentify(worksEntityOptional.get().getIdentify());
        entity.setConfig(worksEntityOptional.get().getContent());
        WorksTemplateEntity saved = worksTemplateRepository.save(entity);
        return WorksTemplateMapStruct.INSTANCE.entityToCreate(saved);
    }

    /**
     * 更新模板
     *
     * @param userProfile 用户信息
     * @param id          模板id
     * @param request     请求
     * @return 响应
     */
    public WorksTemplateUpdateResponse updateTemplate(UserProfile userProfile, String id, WorksTemplateUpdateRequest request) {
        Optional<WorksTemplateEntity> worksTemplateEntityOptional = worksTemplateRepository.findById(Long.parseLong(id));
        if (!worksTemplateEntityOptional.isPresent()) {
            throw new APIRuntimeException(ResultCodeEnum.WORK_TEMPLATE_NOT_EXIST);
        }
        WorksTemplateEntity worksTemplateEntity = worksTemplateEntityOptional.get();
        Long worksId = request.getWorksId();
        Optional<WorksEntity> worksEntityOptional = worksRepository.findById(worksId);
        if (!worksEntityOptional.isPresent()) {
            throw new APIRuntimeException(ResultCodeEnum.WORK_NOT_EXIST);
        }
        WorksTemplateEntity entity = WorksTemplateMapStruct.INSTANCE.updateToEntity(request);
        entity.setId(worksTemplateEntity.getId());
        entity.setCreatedAt(worksTemplateEntity.getCreatedAt());
        entity.setCreator(worksTemplateEntity.getCreator());
        entity.setSort(worksTemplateEntity.getSort());
        entity.setUpdatedAt(new Date());
        entity.setOperator(userProfile.getMobile());
        entity.setIdentify(worksEntityOptional.get().getIdentify());
        entity.setConfig(worksEntityOptional.get().getContent());
        WorksTemplateEntity saved = worksTemplateRepository.save(entity);
        return WorksTemplateMapStruct.INSTANCE.entityToUpdate(saved);
    }

    /**
     * 删除模板
     *
     * @param userProfile 用户信息
     * @param id          模板id
     */
    public void deleteTemplate(UserProfile userProfile, String id) {
        Optional<WorksTemplateEntity> worksTemplateEntityOptional = worksTemplateRepository.findById(Long.parseLong(id));
        if (!worksTemplateEntityOptional.isPresent()) {
            throw new APIRuntimeException(ResultCodeEnum.WORK_TEMPLATE_NOT_EXIST);
        }
        worksTemplateRepository.delete(worksTemplateEntityOptional.get());
    }

}
